﻿//-----------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="AFS">
// Copyright (c) AFS. All rights reserved.
//
//    This file is part of Chatbox.
//
//    Chatbox is free software: you can redistribute it and/or modify
//    it under the terms of the GNU Lesser General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    any later version.
//
//    Chatbox is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU Lesser General Public License for more details.
//
//    You should have received a copy of the GNU Lesser General Public License
//    along with Chatbox. If not, see http://www.gnu.org/copyleft/lesser.html
// </copyright>
//----------------------------------------------------------------------- 

namespace ChatBox
{
    using System.Windows;
    using System.Windows.Threading;

    using ChatBox.Interfaces;
    using ChatBox.UI;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Initializes a new instance of the App class
        /// </summary>
        public App()
        {
            this.DispatcherUnhandledException += this.App_DispatcherUnhandledException;
            this.Logger = Locator.Resolve<ILogger>();
        }

        /// <summary>
        /// Gets where to log unhandled exceptions
        /// </summary>
        public ILogger Logger { get; private set; }

        /// <summary>
        /// Catch and log unhandled exceptions
        /// </summary>
        /// <param name="sender">the event sender</param>
        /// <param name="e">the event params</param>
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
          if (this.Logger != null)
          {
              // detatch the logger to prevent recursion if an error is thrown during logging
              ILogger localLogger = this.Logger;
              this.Logger = null;

              try
              {
                  localLogger.LogException("Exception caught by app", e.Exception);
              }
              finally
              {
                  this.Logger = localLogger;
              }
          }
        }
    }
}
